/**
 * 
 */
package com.shine.icis.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.shine.cotrun.web.comm.SpringContextLoader;
import com.shine.cotrun.web.upload.FileDispatcher;
import com.shine.cotrun.web.upload.FileUtil;
import com.shine.icis.blo.IETLLogService;
import com.shine.icis.config.SysCodeDictLoader;
import com.shine.icis.config.SysConstants;


/**
 * 周期性的执行任务
 * @author zsy
 *
 */
public class PeriodTask extends TimerTask {

	private static final Log log = LogFactory.getLog(PeriodTask.class);
	
	public static final int START_HOUR = 2;//启动时间
	public static final int START_DAY = 1;//启动一个月的第几天
	
	private IETLLogService etlLogService;
	
	public PeriodTask() {
		etlLogService = (IETLLogService)SpringContextLoader.getBean("etlLogService");;
	}
	
	public void run() {
		try {
			//更新数据字典
			SysCodeDictLoader.getInstance().initAllCodeDict();
			
			Calendar c = Calendar.getInstance();
			//每天固定时间执行
			if (c.get(Calendar.HOUR_OF_DAY) == START_HOUR) {
				//清理临时图片文件夹
				log.info("清理临时图片文件夹:");
				FileUtil.cleanTempFile(2);
				
				delRetainSubmitFiles();
				
				//每月一号执行
				if (c.get(Calendar.DAY_OF_MONTH) == START_DAY) {
					//删除配置时间前的备份库数据与日志数据
					etlLogService.txClearHistData();
				}
			}
			
		} catch(Exception e) {
			log.error("定时器运行出错", e);
		}
	}
	
	/**
	 * 删除报送文件的历史记录
	 */
	private void delRetainSubmitFiles() {
		File dir = new File(FileDispatcher.getSaveDir(FileDispatcher.getAbsPath(SysConstants.SUBMIT_FILES_DIR)));
		File[] subDirs = dir.listFiles();
		if (subDirs == null || subDirs.length == 0) {
			return;
		}
		
		String tem = SysCodeDictLoader.getInstance().getSubmitConfValue("FILE_RETAIN_DAYS");
		if (tem == null) {
			return;
		}
		int days = Integer.parseInt(tem);//备份文件保存天数
		if (days < 1) {
			return;
		}
		Calendar now = Calendar.getInstance();
		now.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH) - days);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		int date = Integer.parseInt((sdf.format(now.getTime())));//要删除这天前的文件夹
		for (File subDir : subDirs) {
			String name = subDir.getName();
			name = name.substring(0, name.indexOf("_"));
			if (Integer.parseInt(name) <= date) {//删除这天前的文件夹
				FileUtil.delDir(subDir);
			}
		}
		
	}
}
